<!---
	Copyright 2010 Edward Trudeau, Jeremy Battle
    This software is freely available under the MIT License: http://www.opensource.org/licenses/mit-license.php
    http://ayc.googlecode.com
    
--->

       
        

<!--- form builder

	this page takes a list of fieldnames, form types, lengths, messages, and options and generates our standard cf5 compliant code to send an email.
	
	Format:
	FieldNameInCamelCase,FormType,Required,FormFieldLength,DataType,ErrorMessage,Option1&label1;Option2&label2;option3&label3...,Question1;Question2;Question3
	
	OR 
	
	FieldNameInCamelCase,FormType,Required,FormFieldLength,DataType,ErrorMessage,Option1;Option2;option3...,Question1;Question2;Question3
	
	FormTypes:
		T	Text
		H	Hidden
		S	Select
		R	Radio
		RO Radio with other
		RV Radio, vertical alignment
		ROV Radio with other, vertical alignment
		L	Likert
		C	Checkbox
		CO Checkbox with Other
		CV Checkbox, vertical alignment
		COV Checkbox with Other, vertical alignment
		X	TextArea, defaults to 4 rows and FormFieldLength cols
	
	DataTypes:
		V	Varchar
		X	LongVarchar
		I	Integer
		T	TinyInt
		D	DateTime

 --->
 
 
 <cffunction name="splitAtCaps" hint="returns a string with spaces before each capital letter of the input argument" returntype="string">
	<cfargument name="CamelCaseString" type="string" required="yes">
	

	<cfset var spacedStr = left(arguments.CamelCaseString, 1)>
	<cfset var i = "" />
	<cfset var nextChar = "" />
	<cfset var lastChar = "" />
	

		<cfif len(arguments.CamelCaseString) LTE 2>
			<cfreturn arguments.CamelCaseString>
		</cfif>
		
		<cfloop from="2" to="#len(arguments.CamelCaseString)#" index="i">
			<cfset nextChar = mid(arguments.CamelCaseString, i, 1) />
			<cfset lastChar = mid(arguments.CamelCaseString, i-1, 1) />
			
			<cfif (asc(nextChar) GTE 65 AND asc(nextChar) LTE 90) AND (asc(lastChar) LT 65 OR asc(lastChar) GT 90)>
				<cfset spacedStr = spacedStr & " " & nextChar />
			<cfelse>
				<cfset spacedStr = spacedStr & nextChar />
			</cfif>
		</cfloop>
		
		<cfreturn spacedStr />

</cffunction>

 
 <cfparam name="form.data" default="" />
 <cfparam name="form.towhere" default="#getDirectoryFromPath(getTemplatePath())#" />
 <cfparam name="form.tofile" default="" />
 <cfparam name="form.labelFile" default="labels.txt" />
 <cfparam name="form.styleString" default="
 
 <style>
 	p.altRow, tr.altRow {background-color:##f2ead7; padding:.1em .5em .1em 20em; color:##000;}
	p.qRow, tr.qRow {padding:.1em .5em .1em 20em; color:##000; background-color:##fff;}
	tr.hdr,td.hdr {font-weight:bold; background-color:##dedede;}
	p.grayed {background-color:##ccc !important;}
	p.altRow label, p.qRow label {margin-left:-19em; width:20em;}
	p.smallIndent {padding-left: 3em;}
	td.likert{ text-align: center; }
	p.label {color:##666666; font-weight:bold; padding-left:.5em;}
	span.altRow {background-color:##f2ead7; color:##000;}
	span.qRow{background-color:##fff;color##000;}
	p.altBg{background-color:##f2ead7; margin-bottom:0; padding-top:.5em; padding-bottom:.5em;}
 </style>
 
 " />
 
 <cfparam name="form.dsn" default="AYC" />
 <cfparam name="form.tablename" default="" />
 <cfparam name="form.recreate" default="0" />
 <cfparam name="form.captcha" default="0" />

 
<cfif NOT structKeyExists(form, "fields")>
 	<cfset form.fields = arrayNew(1) />
 </cfif>
 
 <cfif structKeyExists(url, "load")>
 	<cffile action="read" file="#getDirectoryFromPath(getTemplatePath())#\#url.load#.xml" variable="inStr" />
	<cfwddx action="wddx2cfml" input="#inStr#" output="form.fields" />
 </cfif>
 
 
 	<!--- process form submissions --->
 	<cfif structKeyExists(form, "submit") AND form.submit EQ "Build it" >
		<cfif NOT structKeyExists(form, "LastField") or NOT isValid('integer', form.lastField)>
            <h2>No Form.LastField found!</h2>
            <p>Terminating</p>
            <cfdump var="#form#" /><cfabort/>
        </cfif>
        <cfset ind = 0 />
        <cfloop from="1" to="#form.lastField#" index="i">
            <cfif structKeyExists(form, "FieldName_#i#") AND len(trim(form["FieldName_#i#"]))>
                <cfset ind++ />
                <cfset form.fields[ind] = structNew() />
                <cfset form.fields[ind].FieldSeq = "#ind#" />
                <cfset form.fields[ind].FieldName = form["FieldName_#i#"] />
                <cfset form.fields[ind].FieldFullName = form["FieldFullName_#i#"] />
                <cfset form.fields[ind].FieldType = form["FieldType_#i#"] />
                <cfset form.fields[ind].DataType = form["DataType_#i#"] />
                <cfset form.fields[ind].DataMaxLength = form["DataMaxLength_#i#"] />
                <cfset form.fields[ind].FieldClass = form["FieldClass_#i#"] />
                <cfset form.fields[ind].LabelText = form["LabelText_#i#"] />
                <cfset form.fields[ind].LabelClass = form["LabelClass_#i#"] />
                <cfset form.fields[ind].Default = form["Default_#i#"] />
                <cfset form.fields[ind].Validations = arrayNew(1) />
                <cfset jnd = 0 />
                <cfloop from="1" to="#form['LastValidation_#i#']-1#" index="j">
                    <cfif structKeyExists(form, "rule_#i#_#j#") AND len(trim(form['rule_#i#_#j#']))>
                        <cfset jnd++ />
                        <cfset form.fields[ind].Validations[jnd] = structNew() />
                        <cfset form.fields[ind].Validations[jnd].rule = form['rule_#i#_#j#'] />
                        <cfset form.fields[ind].Validations[jnd].ruleVal = form['ruleVal_#i#_#j#'] />
                        <cfset form.fields[ind].Validations[jnd].ruleMsg = form['ruleMsg_#i#_#j#'] />
                    </cfif>
                </cfloop>
                <cfset form.fields[ind].Options = arrayNew(1) />
                <cfset knd = 0 />
                <cfloop from="1" to="#form['LastOption_#i#']-1#" index="k">
                    <cfif structKeyExists(form, "Value_#i#_#k#") AND len(trim(form['Value_#i#_#k#']))>
                        <cfset knd++ />
                        <cfset form.fields[ind].Options[knd] = structNew() />
                        <cfset form.fields[ind].Options[knd].Value = form['Value_#i#_#k#'] />
                        <cfset form.fields[ind].Options[knd].Label = form['Label_#i#_#k#'] />
                    </cfif>
                </cfloop>
                <cfset lnd = 0 />
                <cfset form.fields[ind].Questions = arrayNew(1) />
                <cfloop from="1" to="#form['LastQuestion_#i#']-1#" index="l">
                    <cfif structKeyExists(form, "Question_#i#_#l#") AND len(trim(form['Question_#i#_#l#']))>
                        <cfset lnd++ />
                        <cfset form.fields[ind].Questions[lnd] = form['Question_#i#_#l#'] />
                    </cfif>
                </cfloop>
            </cfif>
        </cfloop>
        <cfset form.fields[1].meta = structNew() />
        <cfset form.fields[1].meta.tableName = form.tableName />
        <cfset form.fields[1].meta.dsn = form.dsn />
        <cfset form.fields[1].meta.fileNameBase = form.toFile />
        
        <cfwddx action="cfml2wddx" input="#form.fields#" output="outstr" />
        <cffile action="write" file="#form.toWhere##form.toFile#_dat.xml" output="#outStr#" />
        
        <cfif len(trim(form.tablename)) AND form.recreate>
            <cfquery name="qDrpTbl" datasource="#form.dsn#">
                IF EXISTS(SELECT 1 FROM sysobjects WHERE Name = '#trim(form.tablename)#' AND xtype = 'U')    DROP TABLE #trim(form.tablename)#
            </cfquery>
            <cfquery name="qCrtTbl" datasource="#form.dsn#" result="qcre8">
                CREATE TABLE #trim(form.tablename)# (
                    ID INT IDENTITY (1,1) PRIMARY KEY CLUSTERED, 
                    CreateDTTM DATETIME NOT NULL DEFAULT (getDate()),
                    
                <cfloop from="1" to="#arrayLen(form.fields)#" index="i">
                    <cfif form.fields[i].fieldType EQ "Likert">
                        <cfloop from="1" to="#arrayLen(form.fields[i].questions)#" index="j">
                            #ucase(form.fields[i].fieldName)#_#j# <cfswitch expression="#form.fields[i].dataType#"><cfcase value="varchar">varchar(255)</cfcase><cfcase value="text">text</cfcase><cfcase value="int">int</cfcase><cfcase value="tinyint">tinyint</cfcase><cfcase value="date">datetime</cfcase></cfswitch>  NULL<cfif j LT arrayLen(form.fields[i].questions)>,</cfif>
                        </cfloop><cfif i LT arrayLen(form.fields)>,</cfif>
                    <cfelseif listFindNoCase("Checkbox,Checkbox Other", form.fields[i].fieldType)>
                        <cfloop from="1" to="#arrayLen(form.fields[i].options)#" index="j">
                            #ucase(form.fields[i].fieldName)#_#j# <cfswitch expression="#form.fields[i].dataType#"><cfcase value="varchar">varchar(255)</cfcase><cfcase value="text">text</cfcase><cfcase value="int">int</cfcase><cfcase value="tinyint">tinyint</cfcase><cfcase value="date">datetime</cfcase></cfswitch>  NULL<cfif j LT arrayLen(form.fields[i].options)>,</cfif>
                        </cfloop>
						<cfif form.fields[i].fieldType EQ "Checkbox Other">
                        	,  #ucase(form.fields[i].fieldName)#_other varchar(255) NULL
                        	,  #ucase(form.fields[i].fieldName)#_otherVal varchar(255) NULL
                        </cfif>
						<cfif i LT arrayLen(form.fields)>,</cfif>
                    <cfelseif form.fields[i].fieldType EQ "Radio Other">
                        #ucase(form.fields[i].fieldName)# <cfswitch expression="#form.fields[i].dataType#"><cfcase value="varchar">varchar(255)</cfcase><cfcase value="text">text</cfcase><cfcase value="int">int</cfcase><cfcase value="tinyint">tinyint</cfcase><cfcase value="date">datetime</cfcase></cfswitch> NULL,
                        #ucase(form.fields[i].fieldName)#_otherVal varchar(255) NULL<cfif i LT arrayLen(form.fields)>,</cfif>
                    <cfelse>
                        #ucase(form.fields[i].fieldName)# <cfswitch expression="#form.fields[i].dataType#"><cfcase value="varchar">varchar(255)</cfcase><cfcase value="text">text</cfcase><cfcase value="int">int</cfcase><cfcase value="tinyint">tinyint</cfcase><cfcase value="date">datetime</cfcase></cfswitch> NULL<cfif i LT arrayLen(form.fields)>,</cfif>
                    </cfif>
                    
                </cfloop>
                )
            </cfquery>
         </cfif> <!--- --->
        
 	</cfif>
    
 	<cfset lastFieldInd = arrayLen(form.fields)+1 />
 	
    <cfset form.fields[lastFieldInd] = structNew() />
    <cfset form.fields[lastFieldInd].FieldSeq = "#lastFieldInd#" />
    <cfset form.fields[lastFieldInd].FieldName = "" />
    <cfset form.fields[lastFieldInd].FieldFullName = "" />
    <cfset form.fields[lastFieldInd].FieldType = "" />
    <cfset form.fields[lastFieldInd].DataType = "" />
    <cfset form.fields[lastFieldInd].DataMaxLength = "" />
    <cfset form.fields[lastFieldInd].FieldClass = "" />
    <cfset form.fields[lastFieldInd].LabelText = "" />
    <cfset form.fields[lastFieldInd].LabelClass = "" />
    <cfset form.fields[lastFieldInd].Default = "" />
    <cfset form.fields[lastFieldInd].Validations = arrayNew(1) />
    <cfset form.fields[lastFieldInd].Validations[1] = structNew() />
    <cfset form.fields[lastFieldInd].Validations[1].rule ="" />
    <cfset form.fields[lastFieldInd].Validations[1].ruleVal ="" />
    <cfset form.fields[lastFieldInd].Validations[1].ruleMsg ="" />
    <cfset form.fields[lastFieldInd].Options = arrayNew(1) />
    <cfset form.fields[lastFieldInd].Options[1] = structNew() />
    <cfset form.fields[lastFieldInd].Options[1].Value ="" />
    <cfset form.fields[lastFieldInd].Options[1].Label ="" />
    <cfset form.fields[lastFieldInd].Questions = arrayNew(1) />
    <cfset form.fields[lastFieldInd].Questions[1] = "" />

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>FormBuilder for AYB</title>
    	<cfif cgi.SERVER_PORT_SECURE>
			<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
        <cfelse>
			<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
        </cfif>
		<script type="text/javascript" src="/js/jquery.tablednd_0_5.js"></script>
        <script type="text/javascript">
          $(document).ready(function() {
            rowTemplate = $('#fieldRow_<cfoutput>#lastFieldInd#</cfoutput>').html();
			setDND();
			setUIFuncs();
			
          });
		  
		  function setDND () {
			  $("#theTable").tableDnD({
				 onDragClass: "drag",
				 onDrop: function(table, row) {
					var rows = table.tBodies[0].rows;
					var currentPos = 0;
					var cRowId = '';
					
					for (var i=1; i<rows.length; i++) {
						cRowId = rows[i].id.split('_')[1];
						currentPos = parseInt(cRowId);
						$('#FieldSeq_'+ currentPos).val(i);
					}
				 }
			});
		  }
		  
		  function setUIFuncs(){
			$('#theTable input.expandable').focus(function(){$(this).addClass('wide');}).blur(function(){$(this).removeClass('wide');});
			$('#theTable textarea').focus(function(){$(this).addClass('bigField');}).blur(function(){$(this).removeClass('bigField');});
			
		  }
		  
		  String.prototype.trim = function () {
				return this.replace(/^\s*/, "").replace(/\s*$/, "");
			}
		
		  function addOption(fldNo, optNo) {
			var nextOpt = parseInt(optNo) + 1;
			var strToAdd = '<tr id="optRow_'+fldNo+'_'+optNo+'"><td><input name="Value_'+fldNo+'_'+optNo+'" id="Value_'+fldNo+'_'+optNo+'" type="text" value="" size="10" class="expandable" /></td>';
			strToAdd += '<td><input name="Label_'+fldNo+'_'+optNo+'" id="Label_'+fldNo+'_'+optNo+'" type="text" value="" size="10" class="expandable" onblur="javascript:addLast('+fldNo+', this.id, \'option\');" /></td>';
			strToAdd += '<td><a href="javascript:void(0);" onclick="javascript:$(\'#optRow_'+fldNo+'_'+optNo+'\').remove();" tabindex="9999">rmv</a></td></tr>'
			$('#lastOption_'+fldNo).val(nextOpt);
			$('#optionTbl_'+fldNo).append(strToAdd);
			setUIFuncs();
		  }
		  
		  function addQuestion(fldNo, optNo) {
			var nextQ = parseInt(optNo) + 1;
			var strToAdd = '<tr id="qstRow_'+fldNo+'_'+optNo+'"><td><textarea name="Question_'+fldNo+'_'+optNo+'" id="Question_'+fldNo+'_'+optNo+'" rows="1" cols="20" onblur="javascript:addLast('+fldNo+', this.id, \'question\');"></textarea></td>';
			strToAdd += '<td><a href="javascript:void(0);" onclick="javascript:$(\'#qstRow_'+fldNo+'_'+optNo+'\').remove();" tabindex="9999">rmv</a></td></tr>'
			$('#lastQuestion_'+fldNo).val(nextQ);
			$('#questionTbl_'+fldNo).append(strToAdd);
			setUIFuncs();
		  }
		  
		  function addValidation(fldNo, optNo) {
			var nextVal = parseInt(optNo) + 1;
			var strToAdd = '<tr id="valRow_'+fldNo+'_'+optNo+'" valign="top"><td><select name="Rule_'+fldNo+'_'+optNo+'" id="Rule_'+fldNo+'_'+optNo+'" size="1" onChange="javascript:setDefMsg(\'RuleMsg_'+fldNo+'_'+optNo+'\', this.options[this.selectedIndex].value, document.getElementById(\'FieldFullName_'+fldNo+'\').value);">';
			strToAdd += '<option></option>';
			strToAdd += '<option value="required">required</option>';
			strToAdd += '<option value="required-dependency">required-dependency</option>';
			strToAdd += '<option value="email">email</option>';
			strToAdd += '<option value="digits">digits</option>';
			strToAdd += '<option value="date">date</option>';
			strToAdd += '<option value="url">url</option>';
			strToAdd += '<option value="min">min</option>';
			strToAdd += '<option value="max>max</option>';
			strToAdd += '<option value="range">range</option>';
			strToAdd += '<option value="number">number</option>';
			strToAdd += '<option value="minLength">minLength</option>';
			strToAdd += '<option value="maxLength">maxLength</option>';
			strToAdd += '<option value="rangeLength">>rangeLength</option>';
			strToAdd += '<option value="equal-to">equal-to</option>';
            strToAdd += '</select></td>';
			strToAdd += '<td><input name="RuleVal_'+fldNo+'_'+optNo+'" id="RuleVal_'+fldNo+'_'+optNo+'" type="text" value="" size="10" class="expandable" /></td>';
			strToAdd += '<td><textarea name="RuleMsg_'+fldNo+'_'+optNo+'" id="RuleMsg_'+fldNo+'_'+optNo+'" rows="3" cols="15" onblur="javascript:addLast('+fldNo+', this.id, \'validation\');"></textarea></td>';
			strToAdd += '<td><a href="javascript:void(0);" onclick="javascript:$(\'#valRow_'+fldNo+'_'+optNo+'\').remove();" tabindex="9999">rmv</a></td></tr>'
			$('#lastValidation_'+fldNo).val(nextVal);
			$('#validationTbl_'+fldNo).append(strToAdd);
			setUIFuncs();
		  }
		  
           function duplicateField(fldNo, rowToCopy) {
			var rawCode = $(rowToCopy).html();
			var nextField = parseInt($('#lastField').val());
			var maxOpts = parseInt($('#lastOption_'+fldNo).val());
			var maxVals = parseInt($('#lastValidation_'+fldNo).val());
			var maxQues = parseInt($('#lastQuestion_'+fldNo).val());
			
			nextField++;
			
			rawCode = replaceRowVals(fldNo, nextField, rawCode);
			rawCode = '<tr valign="top" id="fieldRow_'+nextField+'">'+rawCode+"</tr>"
			$('#lastField').val(nextField);
			$('#theTable').append(rawCode);
			$('#FieldSeq_'+nextField).val(nextField);
				$('#FieldName_'+nextField).val($('#FieldName_'+fldNo).val());
				$('#FieldFullName_'+nextField).val($('#FieldFullName_'+fldNo).val());
				$('#FieldType_'+nextField).val($('#FieldType_'+fldNo).val());
				$('#DataType_'+nextField).val($('#DataType_'+fldNo).val());
				$('#DataMaxLength_'+nextField).val($('#DataMaxLength_'+fldNo).val());
				$('#FieldClass_'+nextField).val($('#FieldClass_'+fldNo).val());
				$('#LabelText_'+nextField).val($('#LabelText_'+fldNo).val());
				$('#LabelClass_'+nextField).val($('#LabelClass_'+fldNo).val());
				$('#Default_'+nextField).val($('#Default_'+fldNo).val());
				for (var i=1; i<maxVals; i++) {
						$('#Rule_'+nextField+'_'+i).val($('#Rule_'+fldNo+'_'+i).val());
						$('#RuleVal_'+nextField+'_'+i).val($('#RuleVal_'+fldNo+'_'+i).val());
						$('#RuleMsg_'+nextField+'_'+i).val($('#RuleMsg_'+fldNo+'_'+i).val());
				}
				for (var i=1; i<maxOpts; i++) {
						$('#Value_'+nextField+'_'+i).val($('#Value_'+fldNo+'_'+i).val());
						$('#Label_'+nextField+'_'+i).val($('#Label_'+fldNo+'_'+i).val());
				}
				for (var i=1; i<maxQues; i++) {
						$('#Question_'+nextField+'_'+i).val($('#Question_'+fldNo+'_'+i).val());
				}
			setDND();
			setUIFuncs();
			/*alert(rawCode);*/
		  }
		  
		  function replaceRowVals(oldVal, newVal, rawCode) {
			var tmpCode = rawCode;
			var ptrn1 = new RegExp("_"+oldVal+"_", "g");
			var ptrn2 = new RegExp("([^0-9])_"+oldVal, "g");
			var ptrn3 = new RegExp(oldVal+", ", "g"); 
			tmpCode = tmpCode.replace(ptrn1, "_"+newVal+"_");
			tmpCode = tmpCode.replace(ptrn2, "$1_"+newVal);
			tmpCode = tmpCode.replace(ptrn3, newVal+", ");
			return tmpCode;
		  }
		  
		  function addField () {
			var nextField = parseInt($('#lastField').val());
			var newRowCode = rowTemplate;
			nextField++;
			newRowCode = replaceRowVals(<cfoutput>#lastFieldInd#</cfoutput>, nextField, newRowCode);
			newRowCode = '<tr valign="top" id="fieldRow_'+nextField+'">'+newRowCode+"</tr>"
			$('#lastField').val(nextField);
			$('#theTable').append(newRowCode);
			$('#FieldSeq_'+nextField).val(nextField);
			setDND();
			setUIFuncs();
		  }
		  
		  
		  function setDefMsg(onObj, forRule, forObjName) {
			if (document.getElementById(onObj)) {
				switch (forRule) {
					case 'required':
						document.getElementById(onObj).value = 'Please supply a value for ' + forObjName;
						break;
					case 'required-dependency':
						document.getElementById(onObj).value = 'You must supply a value for ' + forObjName + ' based on your other choices';
						break;
					case 'email':
						document.getElementById(onObj).value = 'Please supply a valid address for ' + forObjName;
						break;
					case 'digits':
						document.getElementById(onObj).value = 'Please use only the digits 0-9 when filling out ' + forObjName;
						break;
					case 'date':
						document.getElementById(onObj).value = 'Please supply a valid date for ' + forObjName;
						break;
					case 'url':
						document.getElementById(onObj).value = 'Please supply a valid URL, beginning with http:// or https:// for ' + forObjName;
						break;
					case 'min':
						document.getElementById(onObj).value = 'The value you have provided for  ' + forObjName + ' is too small.';
						break;
					case 'max':
						document.getElementById(onObj).value = 'The value you have provided for ' + forObjName + ' is too large.';
						break;
					case 'range':
						document.getElementById(onObj).value = 'The value you have provided for ' + forObjName + ' is not within the valid range.';
						break;
					case 'number':
						document.getElementById(onObj).value = 'Please supply a valid number for ' + forObjName + '; you may use a decimal.';
						break;
					case 'minLength':
						document.getElementById(onObj).value = 'The value you have provided for ' + forObjName + ' is not long enough.';
						break;
					case 'maxLength':
						document.getElementById(onObj).value = 'The value you have provided for ' + forObjName ;
						break;
					case 'rangeLength':
						document.getElementById(onObj).value = 'The value you have provided for ' + forObjName+ ' is not within the valid length range.';
						break;
					case 'equal-to':
						document.getElementById(onObj).value = 'The two values you have supplied for ' + forObjName + 'are not equal.';
						break;
					default:
						document.getElementById(onObj).value = ' ' + forObjName;
						break;
				}

			}
		  }            	
		  
		  function setFullName(baseName, targObj, labelObj) {
				if (!baseName.length) 
					return true;
				else	{
					targObj.value = baseName.replace(/([A-Z][a-z]+)/g, " $1").trim();
					labelObj.value = targObj.value;
					return true;
				}
		  }
		  
		  function setDefType(fType, targObj) {
			  switch (fType) {
				case 'Text Area':
					$('#'+targObj).val('Text');
					break;
				case 'Select':
					$('#'+targObj).val('Tinyint');
					break;
				case 'Radio':
					$('#'+targObj).val('Tinyint');
					break;
				case 'Radio Other':
					$('#'+targObj).val('Tinyint');
					break;
				case 'Checkbox':
					$('#'+targObj).val('Tinyint');
					break;
				case 'Checkbox Other':
					$('#'+targObj).val('Tinyint');
					break;
				case 'Likert':
					$('#'+targObj).val('Tinyint');
					break;
				default:
					$('#'+targObj).val('Varchar');
					break;
			  }
		  }
		  
		  function addLast(curRow, curId, addType) {
			  
			switch (addType) {
				case 'validation':
				
					if (parseInt($('#lastValidation_'+curRow).val())-1==parseInt(curId.split('_')[2])) {
						addValidation(curRow, $('#lastValidation_'+curRow).val());
					}
					break;
				
				case 'option':
				
					if (parseInt($('#lastOption_'+curRow).val())-1==parseInt(curId.split('_')[2])) {
						addOption(curRow, $('#lastOption_'+curRow).val());
					}
					break;
					
				case 'question':
				
					if (parseInt($('#lastQuestion_'+curRow).val())-1==parseInt(curId.split('_')[2])) {
						addQuestion(curRow, $('#lastQuestion_'+curRow).val());
					}
					break;
			}
		  }
		  
		  function setDataLen(whichField, whichType) {
			if (whichType==0) {
				$('#'+whichField).val('50')
		  	} else if (whichType==2) {
				$('#'+whichField).val('500')
			} else {
				$('#'+whichField).val('')
			}
		  }
        </script>
 
 
 <style>
 	body, textarea, td, th, input, select {font-family:Verdana, Arial, sans-serif; font-size:10px;}
	textarea {height:100%; border:1px solid #9CC;}
	table {border-collapse:collapse;}
	#theTable {width:100%; min-width:1600px;}
	#theTable td {border:2px solid #ccc; font-family:Verdana, Geneva, sans-serif;}
	#theTable th {border:2px solid #ccc; background-color:#666; color:#ccc; font-family:Verdana, Geneva, sans-serif;}
	#theTable table.subtbl td, #theTable table.subtbl th {border:none; margin:.1em; padding:.1em;}
	#theTable table.subtbl th {background-color:#ccc; color:#666;}
 	p.altRow, tr.altRow {background-color:#f2ead7; padding:.1em .5em .1em 20em; color:#000;}
	p.qRow, tr.qRow {padding:.1em .5em .1em 20em; color:#000; background-color:#fff;}
	tr.hdr,td.hdr {font-weight:bold; background-color:#dedede;}
	p.grayed {background-color:#ccc !important;}
	p.altRow label, p.qRow label {margin-left:-19em; width:20em;}
	p.smallIndent {padding-left: 3em;}
	td.likert{ text-align: center; }
	p.label {color:#666666; font-weight:bold; padding-left:.5em;}
	span.altRow {background-color:#f2ead7; color:#000;}
	span.qRow{background-color:#fff;color#000;}
	p.altBg{background-color:#f2ead7; margin-bottom:0; padding-top:.5em; padding-bottom:.5em;}
	.wide {width:20em; }
	.bigField {height:20em; width:20em; }
	input:focus, textarea:focus {background-color:#FFC;}
	input[type=text], select {border:1px solid #9CC;}
	.drag {background-color:#FCF;}
 </style>
 
</head>

<body>
 
	<!--- <p>This page takes a list of fieldnames, form types, lengths, messages, and options and generates standard cf7+ compliant code to send an email and optionally to record to a db.</p>
	
	<p><strong>Format:</strong><br>
	FieldNameInCamelCase,FormType,Required(Y,N,W),FormFieldLength,DataType,ErrorMessage,Option1&label1;Option2&label2;option3&label3...,Question1;Question2;Question3</p>
	
	<p>OR</p> 
	
	<p>FieldNameInCamelCase,FormType,Required(Y,N,W),FormFieldLength,DataType,ErrorMessage,Option1;Option2;option3...,Question1;Question2;Question3</p>
	
	<div style="float:left; "><strong>FormTypes:</strong><br />
		<blockquote>
		<strong>T</strong>	Text<br />
		<strong>H</strong>	Hidden<br />
		<strong>S</strong>	Select<br />
		<strong>R</strong>	Radio<br />
        <strong>RO</strong> Radio with Other<br />
		<strong>RV</strong>	Radio, vertical alignment<br />
        <strong>ROV</strong> Radio with Other, vertical alignment<br />
        <strong>L</strong> Likert<br />
		<strong>C</strong>	Checkbox<br />
        <strong>CO</strong> Checkbox with Other<br />
		<strong>CV</strong>	Checkbox, vertical alignment<br />
        <strong>COV</strong> Checkbox with Other, vertical alignment<br />
		<strong>X</strong>	TextArea, defaults to 4 rows and FormFieldLength cols</blockquote></div>
	
	<div style="float:left; "><strong>DataTypes:</strong><br /><blockquote>
		<strong>V</strong>	Varchar<br />
		<strong>X</strong>	LongVarchar<br />
		<strong>I</strong>	Integer<br />
		<strong>T</strong>	TinyInt<br />
		<strong>D</strong>	DateTime</blockquote>
	</div><br style="clear:both; " /> --->
 <form method="post">
 <strong>Fields:</strong><br>
 	<cfoutput><!--- <textarea style="width:90%;height:300px;" name="data">#form.data#</textarea> --->
    <table border="1" id="theTable">
    	<tr class="nodrag nodrop">
        	<th>Seq</th>
        	<th>FieldName</th>
            <th>Full Name</th>
        	<th>FieldType</th>
            <th>FieldClass</th>
        	<th>Label Text</th>
            <th>Label Class</th>
            <th>Default Value</th>
            <th>Validations</th>
            <th>Options</th>
            <th>Questions</th>
            <th></th>
        </tr>
    <cfloop from="1" to="#arrayLen(form.fields)#" index="nextField">
    	<cfset thisField = form.fields[nextField] />
    	<tr valign="top" id="fieldRow_#nextField#">
        	<td><input name="FieldSeq_#nextField#" id="FieldSeq_#nextField#" type="text" value="#thisField['FieldSeq']#" size="3" /></td>
        	<td><input name="FieldName_#nextField#" id="FieldName_#nextField#" type="text" value="#thisField['FieldName']#" onBlur="javascript:setFullName(this.value, document.getElementById('FieldFullName_#nextField#'), document.getElementById('LabelText_#nextField#'));" /></td>
        	<td><input name="FieldFullName_#nextField#" id="FieldFullName_#nextField#" type="text" value="#thisField['FieldFullName']#" class="expandable" /></td>
        	<td><select name="FieldType_#nextField#" id="FieldType_#nextField#" size="1" onChange="setDefType(this.options[this.selectedIndex].value, 'DataType_#nextField#');">
            	<option value="Text"<cfif thisField['FieldType'] EQ "Text"> selected</cfif>>Text</option>
            	<option value="Hidden"<cfif thisField['FieldType'] EQ "Hidden"> selected</cfif>>Hidden</option>
            	<option value="Select"<cfif thisField['FieldType'] EQ "Select"> selected</cfif>>Select</option>
            	<option value="Radio"<cfif thisField['FieldType'] EQ "Radio"> selected</cfif>>Radio</option>
            	<option value="Radio Other"<cfif thisField['FieldType'] EQ "Radio Other"> selected</cfif>>Radio Other</option>
            	<option value="Likert"<cfif thisField['FieldType'] EQ "Likert"> selected</cfif>>Likert</option>
            	<option value="Checkbox"<cfif thisField['FieldType'] EQ "Checkbox"> selected</cfif>>Checkbox</option>
            	<option value="Checkbox Other"<cfif thisField['FieldType'] EQ "Checkbox Other"> selected</cfif>>Checkbox Other</option>
            	<option value="Text Area"<cfif thisField['FieldType'] EQ "Text Area"> selected</cfif>>Text Area</option>
            </select><br />
<br />
			<select name="DataType_#nextField#" id="DataType_#nextField#" size="1" onchange="javascript:setDataLen('DataMaxLength_#nextField#', this.selectedIndex);">
            	<option value="Varchar"<cfif thisField['DataType'] EQ "Varchar"> selected</cfif>>Varchar</option>
            	<option value="Int"<cfif thisField['DataType'] EQ "Int"> selected</cfif>>Int</option>
            	<option value="Text"<cfif thisField['DataType'] EQ "Text"> selected</cfif>>Text</option>
            	<option value="Tinyint"<cfif thisField['DataType'] EQ "Tinyint"> selected</cfif>>Tinyint</option>
            	<option value="Date"<cfif thisField['DataType'] EQ "Date"> selected</cfif>>Date</option>
            </select><br />
<br />
			<input name="DataMaxLength_#nextField#" id="DataMaxLength_#nextField#" type="text" size="4" value="#thisField['DataMaxLength']#" />
</td>
        	<td><input name="FieldClass_#nextField#" id="FieldClass_#nextField#" type="text" value="#thisField['FieldClass']#" size="10" class="expandable" /></td>
        	<td><textarea name="LabelText_#nextField#" id="LabelText_#nextField#" cols="20" rows="4">#thisField['LabelText']#</textarea></td>
        	<td><select name="LabelClass_#nextField#" id="LabelClass_#nextField#" size="1">
            	<option value="inlineLabel"<cfif thisField['LabelClass'] EQ "inlineLabel"> selected</cfif>>inlineLabel</option>
            	<option value="inlineLabel medium"<cfif thisField['LabelClass'] EQ "inlineLabel medium"> selected</cfif>>inlineLabel medium</option>
            	<option value="inlineLabel long"<cfif thisField['LabelClass'] EQ "inlineLabel long"> selected</cfif>>inlineLabel long</option>
            	<option value="blockLabel"<cfif thisField['LabelClass'] EQ "blockLabel"> selected</cfif>>blockLabel</option>
            	<option value="blockLabel medium"<cfif thisField['LabelClass'] EQ "blockLabel medium"> selected</cfif>>blockLabel medium</option>
            	<option value="blockLabel long"<cfif thisField['LabelClass'] EQ "blockLabel long"> selected</cfif>>blockLabel long</option>
            </select></td>
        	<td><input name="Default_#nextField#" id="Default_#nextField#" type="text" value="#thisField['Default']#" size="10" class="expandable" /></td>
        	<td align="right"><table id="validationTbl_#nextField#" class="subtbl">
				<tr>
                	<th>Rule</th>
                    <th>Values</th>
                    <th>Message</th>
                    <th></th>
                </tr>
				
				<cfloop from="1" to="#arrayLen(thisField.Validations)#" index="nextRule">
            	<cfset thisRule = thisField.validations[nextRule] />
            	<tr id="valRow_#nextField#_#nextRule#" valign="top">
                	<td><select name="Rule_#nextField#_#nextRule#" id="Rule_#nextField#_#nextRule#" size="1" onChange="javascript:setDefMsg('RuleMsg_#nextField#_#nextRule#', this.options[this.selectedIndex].value, document.getElementById('FieldFullName_#nextField#').value);">
                        <option></option>
                        <option value="required"<cfif thisRule['Rule'] EQ 'required'> selected</cfif>>required</option>
                        <option value="required-dependency"<cfif thisRule['Rule'] EQ 'required-dependency'> selected</cfif>>required-dependency</option>
                        <option value="email"<cfif thisRule['Rule'] EQ 'email'> selected</cfif>>email</option>
                        <option value="digits"<cfif thisRule['Rule'] EQ 'digits'> selected</cfif>>digits</option>
                        <option value="date"<cfif thisRule['Rule'] EQ 'date'> selected</cfif>>date</option>
                        <option value="url"<cfif thisRule['Rule'] EQ 'url'> selected</cfif>>url</option>
                        <option value="min"<cfif thisRule['Rule'] EQ 'min'> selected</cfif>>min</option>
                        <option value="max"<cfif thisRule['Rule'] EQ 'max'> selected</cfif>>max</option>
                        <option value="range"<cfif thisRule['Rule'] EQ 'range'> selected</cfif>>range</option>
                        <option value="number"<cfif thisRule['Rule'] EQ 'number'> selected</cfif>>number</option>
                        <option value="minLength"<cfif thisRule['Rule'] EQ 'minLength'> selected</cfif>>minLength</option>
                        <option value="maxLength"<cfif thisRule['Rule'] EQ 'maxLength'> selected</cfif>>maxLength</option>
                        <option value="rangeLength"<cfif thisRule['Rule'] EQ 'rangeLength'> selected</cfif>>rangeLength</option>
                        <option value="equal-to"<cfif thisRule['Rule'] EQ 'equal-to'> selected</cfif>>equal-to</option>
                    </select></td>
                	<td><input name="RuleVal_#nextField#_#nextRule#" id="RuleVal_#nextField#_#nextRule#" type="text" value="#thisRule['RuleVal']#" size="10" class="expandable" /></td>
                	<td><textarea name="RuleMsg_#nextField#_#nextRule#" id="RuleMsg_#nextField#_#nextRule#" rows="3" cols="15" onBlur="javascript:addLast(#nextField#, this.id, 'validation');">#thisRule['RuleMsg']#</textarea></td>
                    <td><a href="javascript:void(0);" onClick="javascript:$('##valRow_#nextField#_#nextRule#').remove();" tabindex="9999">rmv</a></td>
                </tr></cfloop><input type="hidden" name="lastValidation_#nextField#" id="lastValidation_#nextField#" value="#arrayLen(thisField.Validations)+1#" />
            </table><br /><a href="javascript:void(0);" onClick="javascript:addValidation(#nextField#, document.getElementById('lastValidation_#nextField#').value)">+ Add validation</a>
            </td>
        	<td align="right"><table id="optionTbl_#nextField#" class="subtbl">
            	<tr>
                	<th>Option Value</th>
                    <th>Option Label</th>
                    <th></th>
                </tr>
                <cfloop from="1" to="#arrayLen(thisField.Options)#" index="nextOption">
                <cfset thisOption = thisField.options[nextOption] />
                <tr id="optRow_#nextField#_#nextOption#">
                	<td><input name="Value_#nextField#_#nextOption#" id="Value_#nextField#_#nextOption#" type="text" value="#thisOption['Value']#" size="10" class="expandable" /></td>
                    <td><input name="Label_#nextField#_#nextOption#" id="Label_#nextField#_#nextOption#" type="text" value="#thisOption['Label']#" size="10" class="expandable" onBlur="javascript:addLast(#nextField#, this.id, 'option');" /></td>
                    <td><a href="javascript:void(0);" onClick="javascript:$('##optRow_#nextField#_#nextOption#').remove();" tabindex="9999">rmv</a></td>
                </tr>
                </cfloop><input type="hidden" name="lastOption_#nextField#" id="lastOption_#nextField#" value="#arrayLen(thisField.Options)+1#" />
            </table><br /><a href="javascript:void(0);" onClick="javascript:addOption(#nextField#, document.getElementById('lastOption_#nextField#').value)">+ Add option</a></td>
        	<td align="right">
            	<table id="questionTbl_#nextField#" class="subtbl">
                <tr>
                	<th>Question</th>
                    <th></th>
                </tr>
                <cfloop from="1" to="#arrayLen(thisField.Questions)#" index="nextQuestion">
                <cfset thisQuestion = thisField.Questions[nextQuestion] />
                <tr id="qstRow_#nextField#_#nextQuestion#">
                	<td><textarea name="Question_#nextField#_#nextQuestion#" id="Question_#nextField#_#nextQuestion#" rows="2" cols="20" onBlur="javascript:addLast(#nextField#, this.id, 'question');">#thisQuestion#</textarea></td>
                    <td><a href="javascript:void(0);" onClick="javascript:$('##qstRow_#nextField#_#nextQuestion#').remove();" tabindex="9999">rmv</a></td>
                </tr>
                </cfloop><input type="hidden" name="lastQuestion_#nextField#" id="lastQuestion_#nextField#" value="#arrayLen(thisField.Questions)+1#" />
                </table><br /><a href="javascript:void(0);" onClick="javascript:addQuestion(#nextField#, document.getElementById('lastQuestion_#nextField#').value)">+ Add question</a>
            </td>
            <td><a href="javascript:void(0);" onClick="javascript:duplicateField(#nextField#, $('##fieldRow_#nextField#'))">Copy</a><br />
<br />
<br /><a href="javascript:void(0);" onClick="javascript:$('##fieldRow_#nextField#').remove();setDND();" tabindex="9999">rmv</a>
</td>
        </tr>
    </cfloop><input type="hidden" name="lastField" id="lastField" value="#nextField-1#" />
    </table>
    <p><a href="javascript:void(0);" onClick="javascript:addField()">+ Add field</a></p>
    
    <br>
<strong>Styles:</strong><br>
	<textarea cols="80" rows="10" name="stylestring">#form.stylestring#</textarea><br>
	<strong>To:</strong> <input type="text" size="60" name="towhere" value="#form.toWhere#" />
	<strong>File name base:</strong> <input type="text" size="20" name="tofile" value="#form.toFile#" /> <strong>Labels:</strong> <input type="text" size="20" name="labelFile" value="#form.labelFile#" /><br>
	<strong>DSN:</strong> <input type="text" size="40" name="dsn" value="#form.dsn#" /> <strong>Tablename:</strong><input type="text" size="20" name="tablename" value="#form.tablename#" />
	<input type="checkbox" value="1" name="recreate"<cfif form.recreate EQ 1> checked</cfif>>  Drop and recreate? <br>
<input type="checkbox" value="1" name="captcha"<cfif form.captcha EQ 1> checked</cfif>> <strong>Protect form? </strong><input type="submit" name="submit" value="Build it" />
 </form></cfoutput>
 <cfsetting showdebugoutput="no">
 
 
 <!--- 
 <cfset outstr = '' />
 <cfset form.data = replaceNoCase(form.data, '"', '&quot;', 'all') />
 
 <cfif len(trim(form.tablename)) AND form.recreate>
 	<cfquery name="qDrpTbl" datasource="#form.dsn#">
		IF EXISTS(SELECT 1 FROM sysobjects WHERE Name = '#trim(form.tablename)#' AND xtype = 'U')    DROP TABLE #trim(form.tablename)#
	</cfquery>
	<cfquery name="qCrtTbl" datasource="#form.dsn#">
		CREATE TABLE #trim(form.tablename)# (
			ID INT IDENTITY (1,1) PRIMARY KEY CLUSTERED, 
			CreateDTTM DATETIME NOT NULL DEFAULT (getDate()),
			<cfset i = 0>
		<cfloop list="#form.data#" delimiters="#chr(10)##chr(13)#" index="nextLine"><cfset i=incrementValue(i) />
        	<cfif listGetAt(nextLine, 2) EQ "L">
            	<cfloop from="1" to="#listLen(listGetAt(nextLine, 8), ';')#" index="j">
            		#ucase(listGetAt(nextLine, 1))#_#j# <cfswitch expression="#listGetAt(nextLine,5)#"><cfcase value="V">varchar(255)</cfcase><cfcase value="X">text</cfcase><cfcase value="I">int</cfcase><cfcase value="T">tinyint</cfcase><cfcase value="D">datetime</cfcase></cfswitch> <cfif listGetAt(nextLine, 3) EQ "Y">NOT</cfif> NULL<cfif j LT listLen(listGetAt(nextLine, 8), ';')>,</cfif>
                </cfloop><cfif i LT listLen(form.data, "#chr(10)##chr(13)#")>,</cfif>
            <cfelseif listFindNoCase("CO,COV,RO,ROV", listGetAt(nextLine, 2))>
            	#ucase(listGetAt(nextLine, 1))# <cfswitch expression="#listGetAt(nextLine,5)#"><cfcase value="V">varchar(255)</cfcase><cfcase value="X">text</cfcase><cfcase value="I">int</cfcase><cfcase value="T">tinyint</cfcase><cfcase value="D">datetime</cfcase></cfswitch> <cfif listGetAt(nextLine, 3) EQ "Y">NOT</cfif> NULL,
                #ucase(listGetAt(nextLine, 1))#_other varchar(255) NULL<cfif i LT listLen(form.data, "#chr(10)##chr(13)#")>,</cfif>
            <cfelse>
            	#ucase(listGetAt(nextLine, 1))# <cfswitch expression="#listGetAt(nextLine,5)#"><cfcase value="V">varchar(255)</cfcase><cfcase value="X">text</cfcase><cfcase value="I">int</cfcase><cfcase value="T">tinyint</cfcase><cfcase value="D">datetime</cfcase></cfswitch> <cfif listGetAt(nextLine, 3) EQ "Y">NOT</cfif> NULL<cfif i LT listLen(form.data, "#chr(10)##chr(13)#")>,</cfif>
            </cfif>
			
		</cfloop>
		)
	</cfquery>
 </cfif>
 
<!--- preserve fields --->
<cfset outstr = outstr & '

<!---
use formBuilderForCSS.cfm to regen:

#form.data#

#form.dsn#
#form.tablename#
#form.labelfile#
#form.toFile#
#form.toWhere#
---> 

' />
 
<!--- everyone needs some style
<cfset outstr = outstr & form.styleString /> --->

<!--- we may need a dsn --->
<cfif len(trim(form.dsn))>
	<cfset outstr = outstr & '

<cfset request.dsn="' & form.dsn & '"/>
<cfset request.baseUNC="#form.toWhere#" />
<cfset request.showCodes = false />
<cfif structKeyExists(url, "sc")>
	<cfset request.showCodes = true />
</cfif>
<cfset showForm = true />' />
</cfif>


 
<!--- all param code --->
<!--- form param code --->
<cfloop list="#form.data#" delimiters="#chr(10)##chr(13)#" index="nextLine">
	<cfif listGetAt(nextLine, 2) EQ "L">
    	<cfloop from="1" to="#listLen(listGetAt(nextLine, 8), ';')#" index="i">
			<cfset outstr = outstr & '
        <cfparam name="form.#listGetAt(nextLine, 1)#_#i#" default="" />' />
        </cfloop>
    <cfelseif listFindNoCase("CO,COV,RO,ROV", listGetAt(nextLine, 2))>
     	<cfset outstr = outstr & '
    <cfparam name="form.#listGetAt(nextLine, 1)#" default="" />
    <cfparam name="form.#listGetAt(nextLine, 1)#_other" default="" />' />
    <cfelse>
		<cfset outstr = outstr & '
    <cfparam name="form.#listGetAt(nextLine, 1)#" default="" /> '/>
    </cfif>
</cfloop>
<!--- question paramcode --->
<cfloop list="#form.data#" delimiters="#chr(10)##chr(13)#" index="nextLine">
	<cfset outstr = outstr & '
    <cfparam name="variables.q#listGetAt(nextLine, 1)#" default="#listGetAt(nextLine,1)#" />' />
</cfloop>

<!--- set labels from text file --->
<cfset outstr = outstr & '

<cfif fileExists("##request.baseUNC###form.labelFile#")>
	<cffile action="read" file="##request.baseUNC###form.labelFile#" variable="fileLabels" />
	<cfloop list="##fileLabels##" delimiters="##chr(10)####chr(13)##" index="nextLabel">
    	<cfset nextVar = listGetAt(nextLabel, 1, "=") />
        <cfset nextVal = listGetAt(nextLabel, 2, "=") />
        <cfif structKeyExists(variables, nextVar)>
        	<cfset variables["##nextVar##"] = nextVal />
        </cfif>
    </cfloop>
</cfif>

' />

<!--- validation code --->
<cfset outstr = outstr & '
<!--- handle form submissions --->
<cfset errMsg = "" />
<cfset warnMsg = "" />
<cfif structKeyExists(form, "submit")>' />
	
<cfloop list="#form.data#" delimiters="#chr(10)##chr(13)#" index="nextLine">
	<cfif listGetAt(nextLine, 3) EQ 'Y'>
    	<cfif listGetAt(nextLine, 2) EQ "L">
        	<cfloop from="1" to="#listLen(listGetAt(nextLine, 8), ';')#" index="i">
				<cfset outstr = outstr & '
        <cfif NOT len(trim(form.#listGetAt(nextLine,1)#_#i#))>
            <cfset errMsg = errMsg & "<li>#listGetAt(listGetAt(nextLine,8), i, ';')#</li>" />
        </cfif>' />
            </cfloop>
        <cfelse>
        	<cfset outstr = outstr & '
	<cfif NOT len(trim(form.#listGetAt(nextLine,1)#))>
		<cfset errMsg = errMsg & "<li>#listGetAt(nextLine,6)#</li>" />
	</cfif>' />
        </cfif>
	</cfif>
        
    <cfif listGetAt(nextLine, 3) EQ  'W'>
    	<cfif listGetAt(nextLine, 2) EQ "L">
        	<cfloop from="1" to="#listLen(listGetAt(nextLine, 8), ';')#" index="i">
				<cfset outstr = outstr & '
        <cfif NOT len(trim(form.#listGetAt(nextLine,1)#_#i#))>
            <cfset warnMsg = warnMsg & "<li>#listGetAt(listGetAt(nextLine,8), i, ';')#</li>" />
        </cfif>' />
            </cfloop>
        <cfelse>
        	<cfset outstr = outstr & '
	<cfif NOT len(trim(form.#listGetAt(nextLine,1)#))>
		<cfset warnMsg = warnMsg & "<li>#listGetAt(nextLine,6)#</li>" />
	</cfif>' />
        </cfif>
	</cfif>
</cfloop>

<!--- handle captcha if included --->
<cfif form.captcha>
	<cfset outstr = outstr & '
<cfif NOT structKeyExists(form, "imagecode") OR NOT isNumeric(form.imageCode)
	OR NOT structKeyExists(form, "hashcode") OR NOT len(form.hashcode)>
	<cfmodule template="##request.ctPath##stdError.cfm" errMsg="<li>This form requires a captcha." errTitle="Oops!  There was an error submitting your form....please try again!" />
<cfelse>
	<cfset dechash = decrypt(urldecode(form.hashcode), "LAKwu4ovilqwroi3wy5vasnakjrbcliubwe") />
	<cfif dechash NEQ form.imagecode>
		<cfset errMsg = errMsg & "<li>Your number does not match the image.</li>" />
	</cfif>
</cfif>

 ' />
</cfif>

<!--- halt on errors code --->
<cfset outstr = outstr & '
	<cfif len(errMsg)>
		<cfmodule template="##request.ctPath##stdError.cfm" errMsg="##errMsg##" errTitle="You missed some values..." Subtitle="Please use your back button to correct the following fields." />
	<cfelseif len(warnMsg) AND form.submit NEQ "I am satisfied with my answers - submit now">
		<cfmodule template="##request.ctPath##stdError.cfm" errMsg="##warnMsg##" errTitle="You chose NOT to answer the following fields:" Subtitle="If this is correct, click the <strong>I am Satisfied with my Answers - Submit Now</strong> button, below.  Otherwise, please complete your answers in the form below and click <strong>Try Again</strong>." />
	<cfelse>
	<!--- submission is ok! --->
	
	<cfset ResultsHTML = "
	<table class=''formtable''>" />
	' />
	
 
	<cfloop  list="#form.data#" delimiters="#chr(10)##chr(13)#" index="nextLine">
		<cfif listGetAt(nextLine, 2) EQ "X">
			<cfset outstr = outstr & '
		<cfset ResultsHTML = ResultsHTML & 
		"<tr>
			<td class=''hdr'' colspan=''2''>#splitAtCaps(listGetAt(nextLine, 1))#</td>
		</tr>
		<tr>
			<td class=''dta'' colspan=''2'' style=''padding-left:1em;''>##HTMLEditFormat(form.#listGetAt(nextLine, 1)#)##</td>
		</tr>" />' />
        <cfelseif listGetAt(nextLine, 2) EQ "L">
        	<cfset outstr = outstr & '
		<cfset ResultsHTML = ResultsHTML & 
		"<tr>
			<td class=''hdr'' colspan=''2''>#splitAtCaps(listGetAt(nextLine, 1))#</td>
		</tr>" />' />
        	<cfloop from="1" to="#listLen(listGetAt(nextLine, 8), ';')#" index="i">
            	<cfset outstr = outstr & '
		<cfset ResultsHTML = ResultsHTML & 
		"<tr>
			<td class=''hdr''>#listGetAt(listGetAt(nextLine, 8), i, ';')#</td>
			<td class=''dta'' style=''padding-left:1em;''>##HTMLEditFormat(form.#listGetAt(nextLine, 1)#_#i#)##</td>
		</tr>" />' />
            </cfloop>
		
		<cfelse>
			<cfset outstr = outstr & '
		<cfset ResultsHTML = ResultsHTML & 
		"<tr>
			<td class=''hdr''>#splitAtCaps(listGetAt(nextLine, 1))#</td>
			<td class=''dta''>##HTMLEditFormat(form.#listGetAt(nextLine, 1)#)##</td>
		</tr>" />' />
        	<cfif listFindNoCase("CO,COV,RO,ROV", listGetAt(nextLine, 2))>
            	<cfset outstr = outstr & '
					<cfset ResultsHTML = ResultsHTML & 
					"<tr>
						<td class=''hdr''>#splitAtCaps(listGetAt(nextLine, 1))# - other</td>
						<td class=''dta''>##HTMLEditFormat(form.#listGetAt(nextLine, 1)#_other)##</td>
					</tr>" />' />
            </cfif>
		</cfif>
	</cfloop>
	
<cfset outstr = outstr & '		
		<cfmail to="trudeaue@cua.edu" from="noreply@cua.edu" Subject="FORM SUBMISSION: a web form has been submitted" type="html">
		#replaceNoCase(form.styleString,"##", "####", "all")#
			A form submission succeeded from your web page on ##dateFormat(now(),"dddd, mmmm d, yyyy")## at ##timeFormat(now(),"h:mm tt")##
			
			##ResultsHTML##
		</cfmail>
		
		<cfif structKeyExists(request, "dsn")>
			<cfquery name="qInsRec" datasource="##request.dsn##">
				INSERT INTO #form.tablename#
					(' />
	<cfset columnList = '' />
	<cfset paramList = '' />
	<cfloop  list="#form.data#" delimiters="#chr(10)##chr(13)#" index="nextLine">
    	<cfif listGetAt(nextLine, 2) EQ "L">
        	<cfloop from="1" to="#listLen(listGetAt(nextLine, 8), ';')#" index="j">
            	<cfset columnList = listAppend(columnList, "#listGetAt(nextLine,1)#_#j#") />
                <cfset nextParam = '
					<cfqueryparam  cfsqltype="' />
				<cfswitch expression="#listGetAt(nextLine,5)#"><cfcase value="V"><cfset nextParam = nextParam & 'cf_sql_varchar' /></cfcase><cfcase value="X"><cfset nextParam = nextParam & 'cf_sql_longvarchar' /></cfcase><cfcase value="I"><cfset nextParam = nextParam & 'cf_sql_integer' /></cfcase><cfcase value="T"><cfset nextParam = nextParam & 'cf_sql_tinyint' /></cfcase><cfcase value="D"><cfset nextParam = nextParam & 'cf_sql_datetime' /></cfcase></cfswitch>
				<cfset nextParam = nextParam & '#iif(listGetAt(nextLine,5) EQ "V", de('" maxlength="100"'), de('"'))# value="##trim(form.#listGetAt(nextLine,1)#_#j#)##" null="##iif(trim(form.#listGetAt(nextLine,1)#_#j#) EQ '''', de(''yes''), de(''no''))##" />'/>
				<cfset paramList = listAppend(paramList, nextParam) />
				</cfloop>
        <cfelseif listFindNoCase("CO,COV,RO,ROV", listGetAt(nextLine, 2))>
        	<cfset columnList = listAppend(columnList, listGetAt(nextLine,1)) />
        	<cfset columnList = listAppend(columnList, listGetAt(nextLine,1)  & "_other") />
			<cfset nextParam = '
				<cfqueryparam  cfsqltype="' />
            <cfswitch expression="#listGetAt(nextLine,5)#"><cfcase value="V"><cfset nextParam = nextParam & 'cf_sql_varchar' /></cfcase><cfcase value="X"><cfset nextParam = nextParam & 'cf_sql_longvarchar' /></cfcase><cfcase value="I"><cfset nextParam = nextParam & 'cf_sql_integer' /></cfcase><cfcase value="T"><cfset nextParam = nextParam & 'cf_sql_tinyint' /></cfcase><cfcase value="D"><cfset nextParam = nextParam & 'cf_sql_datetime' /></cfcase></cfswitch>
            <cfset nextParam = nextParam & '#iif(listGetAt(nextLine,5) EQ "V", de('" maxlength="100"'), de('"'))# value="##trim(form.#listGetAt(nextLine,1)#)##" null="##iif(trim(form.#listGetAt(nextLine,1)#) EQ '''', de(''yes''), de(''no''))##" />'/>
            <cfset paramList = listAppend(paramList, nextParam) />
            <cfset nextParam = '
				<cfqueryparam  cfsqltype="cf_sql_varchar" maxlength="100" value="##trim(form.#listGetAt(nextLine,1)#_other)##" null="##iif(trim(form.#listGetAt(nextLine,1)#_other) EQ '''', de(''yes''), de(''no''))##" />'/>
            <cfset paramList = listAppend(paramList, nextParam) />
        <cfelse>
        	<cfset columnList = listAppend(columnList, listGetAt(nextLine,1)) />
            <cfset nextParam = '
				<cfqueryparam  cfsqltype="' />
            <cfswitch expression="#listGetAt(nextLine,5)#"><cfcase value="V"><cfset nextParam = nextParam & 'cf_sql_varchar' /></cfcase><cfcase value="X"><cfset nextParam = nextParam & 'cf_sql_longvarchar' /></cfcase><cfcase value="I"><cfset nextParam = nextParam & 'cf_sql_integer' /></cfcase><cfcase value="T"><cfset nextParam = nextParam & 'cf_sql_tinyint' /></cfcase><cfcase value="D"><cfset nextParam = nextParam & 'cf_sql_datetime' /></cfcase></cfswitch>
            <cfset nextParam = nextParam & '#iif(listGetAt(nextLine,5) EQ "V", de('" maxlength="100"'), de('"'))# value="##trim(form.#listGetAt(nextLine,1)#)##" null="##iif(trim(form.#listGetAt(nextLine,1)#) EQ '''', de(''yes''), de(''no''))##" />'/>
            <cfset paramList = listAppend(paramList, nextParam) />
        </cfif>
		
		
	</cfloop>
		<cfset outstr = outstr & replace(columnList, ",", ", ", "all") />
<cfset outstr = outstr & '						
					)
				VALUES (' />
				
<cfset outstr = outstr & paramList & '		
				)
			</cfquery>
		</cfif>
	
		<cfset structClear(form) />
		<h2>Thank you for your submission!</h2>
		<p>To return to the home page, <a href="">click here</a>.</p>
		<cfset showForm = false />
	</cfif>
<!--- end form validation and submission code --->
</cfif>' />

<cfset outstr = outstr & '
<cfif showForm>
<cfform name="autoform" method="post">
	<fieldset>' />

<cfset qCount = 0 />
<cfset labelStr = "" />
<cfloop list="#form.data#" delimiters="#chr(10)##chr(13)#" index="nextLine">
	<cfset labelStr = labelStr & "q#listGetAt(nextLine, 1)#=#splitAtCaps(listGetAt(nextLine, 1))#
" />
	<cfoutput><p>#nextLine#</p></cfoutput><cfflush>
    <cfset qCount = incrementValue(qCount) />
	<cfset outstr = outstr & '
		<p class="#iif(qCount MOD 2 is 1, de('qRow'), de('altRow'))#">' />
	<cfswitch expression="#listGetAt(nextLine,2)#">
		<cfcase value="T">
			<cfset outstr = outstr & '
			<label for="#listGetAt(nextLine,1)#"><cfoutput>##variables.q#listGetAt(nextLine,1)###</cfoutput></label>
			<cfinput type="text" id="#listGetAt(nextLine,1)#" name="#listGetAt(nextLine,1)#" value="##form.#listGetAt(nextLine,1)###" #iif(listGetAt(nextLine, 3) EQ "Y", de('required="yes"'), de('required="no"'))# message="#listGetAt(nextLine, 6)#" size="#listGetAt(nextLine, 4)#" maxlength="100" /><cfif request.showCodes> <span class="alert"><cfoutput>#listGetAt(nextLine,1)#</cfoutput></span></cfif></p>' />
		</cfcase>
		<cfcase value="H">
			<cfset outstr = outstr & '
			<label for="#listGetAt(nextLine,1)#"><cfoutput>##variables.q#listGetAt(nextLine,1)###</cfoutput></label>
			<input type="hidden"  id="#listGetAt(nextLine,1)#" name="#listGetAt(nextLine,1)#" value="##form.#listGetAt(nextLine,1)###" /><cfif request.showCodes> <span class="alert"><cfoutput>#listGetAt(nextLine,1)#</cfoutput></span></cfif></p>' />
		</cfcase>
		<cfcase value="S">
			<cfset outstr = outstr & '
			<label for="#listGetAt(nextLine,1)#"><cfoutput>##variables.q#listGetAt(nextLine,1)###</cfoutput></label>
			<cfselect  id="#listGetAt(nextLine,1)#" name="#listGetAt(nextLine,1)#" selected="##form.#listGetAt(nextLine,1)###" #iif(listGetAt(nextLine, 3) EQ "Y", de('required="yes"'), de('required="no"'))# message="#listGetAt(nextLine, 6)#" size="#listGetAt(nextLine, 4)#">' />
			<cfloop list="#listGetAt(nextLine,7)#" index="nextopt" delimiters=";">
				<cfset outstr = outstr & '
				<option value="#listGetAt(nextOpt,1,'&')#" <cfif form.#listGetAt(nextLine,1)# EQ "#listGetAt(nextOpt, 1, '&')#"> selected</cfif>>' /> <cfif listLen(nextOpt, "&") EQ 2><cfset outstr = outstr & listGetAt(nextOpt,2,"&") /><cfelse><cfset outstr = outstr & listGetAt(nextOpt,1,"&") /></cfif>
				<cfset outstr = outstr & '</option>' />
			</cfloop>
			<cfset outstr = outstr & '
				</cfselect><cfif request.showCodes> <span class="alert"><cfoutput>#listGetAt(nextLine,1)#</cfoutput></span></cfif></p>'>
		</cfcase>
		<cfcase value="R,RO,RV,ROV">
			<cfset outstr = outstr & '
			<label for="#listGetAt(nextLine,1)#"><cfoutput>##variables.q#listGetAt(nextLine,1)###</cfoutput><cfif request.showCodes> <span class="alert"><cfoutput>#listGetAt(nextLine,1)#</cfoutput></span></cfif></label>
			' />
			<cfloop list="#listGetAt(nextLine,7)#" index="nextopt" delimiters=";">
				<cfset outstr = outstr & '
				<cfinput type="radio" name="#listGetAt(nextLine,1)#" value="#listGetAt(nextOpt,1,'&')#" #iif(listGetAt(nextLine, 3) EQ "Y", de('required="yes"'), de('required="no"'))# message="#listGetAt(nextLine, 6)#" checked="##iif(form.#listGetAt(nextLine,1)# EQ ''#listGetAt(nextOpt,1,'&')#'', de(''yes''), de(''no''))##" />' />
				<cfif listLen(nextOpt, "&") EQ 2><cfset outstr = outstr & ' ' & listGetAt(nextOpt,2,"&") /><cfelse><cfset outstr = outstr & ' ' & listGetAt(nextOpt,1,"&") /></cfif> <cfif listGetAt(nextLine, 2) EQ "RV" OR listGetAt(nextLine, 2) EQ "ROV"><cfset outstr = outstr & '<br /><label>&nbsp;</label>' /></cfif>
			</cfloop>
            <cfif listGetAt(nextLine, 2) EQ "ROV" OR listGetAt(nextLine, 2) EQ "RO">
            	<cfset outstr = outstr & '
				<cfinput type="radio" name="#listGetAt(nextLine,1)#" value="0" #iif(listGetAt(nextLine, 3) EQ "Y", de('required="yes"'), de('required="no"'))# message="#listGetAt(nextLine, 6)#" checked="##iif(form.#listGetAt(nextLine,1)# EQ ''0'', de(''yes''), de(''no''))##" /> Other: <cfinput type="text" name="#listGetAt(nextLine, 1)#_other" value="##form.#listGetAt(nextLine,1)#_other##" maxlength="100" />' /> 
            </cfif>
			<cfset outstr = outstr & '
			</p>' />
		</cfcase>
		<cfcase value="L"><!--- likert scale --->
			<cfset outstr = outstr & '
				<label for="#listGetAt(nextLine,1)#"><cfoutput>##variables.q#listGetAt(nextLine,1)###</cfoutput></label>
				<table class="likert"><tr class="#iif(qCount MOD 2 is 1, de('qRow'), de('altRow'))#"><td>&nbsp;</td>' />
			<cfloop list="#listGetAt(nextLine,7)#" index="nextopt" delimiters=";">
            	<cfif listLen(nextOpt, "&") EQ 2>
					<cfset outstr = outstr & '
					<td class="hdr likert">#listGetAt(nextOpt, 2, "&")#</td>' />
                <cfelse>
                	<cfset outstr = outstr & '
					<td class="hdr likert">#nextOpt#</td>' />
                </cfif>
				
			</cfloop>
            <cfset outstr = outstr & '
			</tr>' />
            <cfloop from="1" to="#listLen(listGetAt(nextLine, 8), ';')#" index="i">
            	<cfset nextQuestion = listGetAt(listGetAt(nextLine, 8), i, ';') />
            	<cfset outstr = outstr & '
				<tr class="#iif(qCount MOD 2 is 1, de('qRow'), de('altRow'))#"><td class="dta">#nextQuestion#<cfif request.showCodes> <span class="alert"><cfoutput>#listGetAt(nextLine,1)#_#i#</cfoutput></span></cfif></td>' />
                <cfloop list="#listGetAt(nextLine,7)#" index="nextopt" delimiters=";">
                    <cfset outstr = outstr & '
                    <td class="dta likert"><cfinput type="radio" name="#listGetAt(nextLine,1)#_#i#" value="#listGetAt(nextOpt,1,'&')#" #iif(listGetAt(nextLine, 3) EQ "Y", de('required="yes"'), de('required="no"'))# message="#listGetAt(nextLine, 6)#" checked="##iif(form.#listGetAt(nextLine,1)#_#i# EQ ''#listGetAt(nextOpt,1,'&')#'', de(''yes''), de(''no''))##" /></td>' />
                </cfloop>
                <cfset outstr = outstr & '
				</tr>' />
            </cfloop>
            <cfset outstr = outstr & '
			</table></p>' />
		</cfcase>
		<cfcase value="C,CO,CV,COV">
			<cfset outstr = outstr & '
			<label for="#listGetAt(nextLine,1)#"><cfoutput>##variables.q#listGetAt(nextLine,1)###</cfoutput></label>
			' />
			<cfloop list="#listGetAt(nextLine,7)#" index="nextopt" delimiters=";">
				<cfset outstr = outstr & '
				<cfinput type="checkbox" name="#listGetAt(nextLine,1)#" value="#listGetAt(nextOpt,1,'&')#" #iif(listGetAt(nextLine, 3) EQ "Y", de('required="yes"'), de('required="no"'))# message="#listGetAt(nextLine, 6)#" checked="##iif(form.#listGetAt(nextLine,1)# EQ "#listGetAt(nextOpt,1,'&')#", de("yes"), de("no"))##" /> <cfif request.showCodes> <span class="alert"><cfoutput>#listGetAt(nextLine,1)#</cfoutput></span></cfif>' />
				<cfif listLen(nextOpt, "&") EQ 2><cfset outstr = outstr & ' ' & listGetAt(nextOpt,2,"&") /><cfelse><cfset outstr = outstr & ' ' & listGetAt(nextOpt,1,"&") /></cfif> <cfif listGetAt(nextLine, 2) EQ "CV" OR listGetAt(nextLine, 2) EQ "COV"><cfset outstr = outstr & '<br /><label>&nbsp;</label>' /></cfif>
			</cfloop>
            <cfif listGetAt(nextLine, 2) EQ "COV" OR listGetAt(nextLine, 2) EQ "CO">
            	<cfset outstr = outstr & '
				<cfinput type="checkbox" name="#listGetAt(nextLine,1)#" value="0" #iif(listGetAt(nextLine, 3) EQ "Y", de('required="yes"'), de('required="no"'))# message="#listGetAt(nextLine, 6)#" checked="##iif(form.#listGetAt(nextLine,1)# EQ ''0'', de(''yes''), de(''no''))##" /> Other: <cfinput type="text" name="#listGetAt(nextLine, 1)#_other" value="##form.#listGetAt(nextLine,1)#_other##" maxlength="100" />' /> 
            </cfif>
		</cfcase>
		<cfcase value="X">
			<cfset outstr = outstr & '
			<label for="#listGetAt(nextLine,1)#" class="long"><cfoutput>##variables.q#listGetAt(nextLine,1)###</cfoutput><cfif request.showCodes> <span class="alert"><cfoutput>#listGetAt(nextLine,1)#</cfoutput></span></cfif></label>
			<textarea name="#listGetAt(nextLine,1)#" cols="#listGetAt(nextLine,4)#"><cfoutput>##form.#listGetAt(nextLine,1)###</cfoutput></textarea></p>' />
		</cfcase>
	</cfswitch>
    <!--- <cfset outstr = outstr & '
	</tr>' /> --->
</cfloop>

<cfif form.captcha>
	<cfset outstr = outstr & '
	<cfset myseed = randrange(10000,99999) />
	<cfset myencseed = encrypt(myseed, "LAKwu4ovilqwroi3wy5vasnakjrbcliubwe") />
	<p>
	<cfoutput>
		<label for="captcha" class="medium">Type this number <img src="https://secure.cua.edu/formsec/?gethash=##urlencodedformat(myencseed)##" border="1" alt="Please type the text you see here in the box at right."> into the box: </label>
		<input type="text" name="imagecode" maxlength="5" size="5" /><input type="hidden" name="hashcode" value="##urlencodedformat(myencseed)##" /></cfoutput></p>' />
</cfif>

<cfset outstr = outstr & '
	<cfif structKeyExists(form, "submit") AND len(warnMsg)>
		<p><label for="submit" class="medium">&nbsp;</label>
		<input type="submit" name="submit" value="I am Satisfied with my Answers - Submit Now" /></p>
	</cfif>
' />

<cfset outstr = outstr & '
		<p><label for="submit" class="medium">&nbsp;</label>
			<cfif len(errMsg) or len(warnMsg)><input type="submit" name="submit" value="Try Again" /><cfelse><input type="submit" name="submit" value="Submit" /></cfif></p>
	</fieldset>
</cfform>
</cfif><!--- showform --->' />

<pre>
<cfoutput>#htmlEditFormat(outstr)#</cfoutput>
</pre>

<cfif directoryExists(trim(form.towhere)) AND len(trim(form.tofile))>
	<cffile action="write" file="#trim(form.towhere)##trim(form.tofile)#" output="#outstr#" />
        <p>Wrote file.</p>
    <cfif len(trim(form.labelFile))>
    	<cffile action="write" file="#trim(form.towhere)##trim(form.labelFile)#" output="#labelStr#" />
        <p>Wrote label file.</p>
    </cfif>
<cfelseif  structKeyExists(form, "submit")>
	<p>Yeah, couldn't write to <cfoutput>#form.toWhere##form.toFile#</cfoutput></p>
</cfif>
 
 
 
 
 
 
  --->
 
 <cfif isDefined('qcre8')>
 	<cfoutput><pre>#htmlEditFormat(qCre8.sql)#</pre></cfoutput>
 </cfif>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 </body>
</html>


